package cn.good.yan.sf.t7;


import java.util.Iterator;

/**
 * 7 栈 - 基于 链表实现
 *
 * @author shengren.yan
 * @create 2024-07-27
 */
public class LinkListStack<E> implements Stack<E>, Iterable<E> {

    static class Node<E> {
        private E value;
        private Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    // 栈顶
    private Node<E> head = new Node<>(null, null);
    private int size = 0;
    private int num = 0;

    public LinkListStack(int num) {
        this.num = num;
    }

    // 1 2 3 4 5
    @Override
    public boolean push(E e) {
        if (isFull()) {
            return false;
        }
        Node<E> node = new Node<>(e, head.next);
        head.next = node;
        size++;
        return true;
    }

    @Override
    public E pol() {
        if (isEmpty()) {
            return null;
        }
        Node<E> node = head.next;
        head.next = node.next;
        size--;
        return node.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        Node<E> node = head.next;
        return node.value;
    }

    @Override
    public boolean isEmpty() {
//        return head.next == null;
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == num;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> node = head.next;

            @Override
            public boolean hasNext() {
                return node != null;
            }

            @Override
            public E next() {
                E value = node.value;
                node = node.next;
                return value;
            }
        };
    }

    public static void main(String[] args) {
        LinkListStack<Integer> q = new LinkListStack<>(5);
        System.out.println("移除元素：" + q.pol());
        System.out.println("获取头元素：" + q.peek());
        System.out.println("添加元素：" + q.push(1));
        System.out.println("添加元素：" + q.push(2));
        System.out.println("添加元素：" + q.push(3));
        System.out.println("添加元素：" + q.push(4));
        System.out.println("添加元素：" + q.push(5));
        System.out.println("添加元素：" + q.push(6));
        System.out.println("添加元素：" + q.push(7));
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("获取头元素：" + q.peek());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("--------------");
    }

}
